package com.dpying.mgtv.autoplay.autoplay;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.util.HashMap;
import java.util.Map;


public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private final String TAG = "Play Activity";
    private final int NETWORKPERMISSION = 0;
    private final int PHONEPERMISSION = 1;

    private void requestPermission(){
        ActivityCompat.requestPermissions(this,  new String[]{Manifest.permission.INTERNET, Manifest.permission.READ_PHONE_STATE}, PHONEPERMISSION);
    }

    //权限处理
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults){

        switch (requestCode){
            case NETWORKPERMISSION:
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    Log.d(TAG, "网络权限允许");

                } else {
                    Log.d(TAG, "网络权限拒绝");
                }
                return;
            case PHONEPERMISSION:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d(TAG, "读取电话状态允许");
                } else {
                    Log.d(TAG, "读取电话状态拒绝");
                }
                return;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestPermission();

        Log.d("Play", "On Create");
        setContentView(R.layout.activity_main);
        Button testBtn = findViewById(R.id.test);
        Button startServiceBtn = findViewById(R.id.startService);
        Button stopServiceBtn = findViewById(R.id.stopService);
        testBtn.setOnClickListener(this);
        startServiceBtn.setOnClickListener(this);
        stopServiceBtn.setOnClickListener(this);
       // startForegroundService();;
        getDeviceInfo();
        super.onCreate(savedInstanceState);
    }

    private void getDeviceInfo(){
        final TelephonyManager tm = (TelephonyManager) getBaseContext().getSystemService(Context.TELEPHONY_SERVICE);
        final String tmDevice, tmSerial, androidId;
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
            Log.d(TAG, "无法获取权限");
            return;
        }

        EditText serialNumberText = findViewById(R.id.serialNumber);
        serialNumberText.setText(Build.SERIAL);

        tmDevice = "" + tm.getDeviceId();
        tmSerial = "" + tm.getSimSerialNumber();
        androidId = "" + android.provider.Settings.Secure.getString(getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
        Log.d(TAG, String.format("%s %s %s %s", tmDevice, tmSerial, androidId,  Build.SERIAL));
    }

    private Map<String,String> getPlayParams(){
        TextView vvid = findViewById(R.id.vid);
        TextView vcid = findViewById(R.id.cid);
        TextView servierIPView = findViewById(R.id.serverIP);
        TextView serialNumberView = findViewById(R.id.serialNumber);

        String cid = vcid.getText().toString().trim();
        String vid = vvid.getText().toString().trim();
        String serverIP = servierIPView.getText().toString().trim();
        String serialNumber = serialNumberView.getText().toString().trim();
        Intent current = getIntent();

        String adbPassIP = current.getStringExtra("ip");
        String adbPassserialNumber = current.getStringExtra("id");
        if(!Utils.isNull(adbPassIP)) serverIP = adbPassIP;
        if(!Utils.isNull(adbPassserialNumber)) serialNumber = adbPassserialNumber;

        Log.d("Play Activity", String.format("cid: %s, vid: %s, sip: %s, did: %s",cid, vid, serverIP, adbPassserialNumber));

        if(cid.isEmpty() || vid.isEmpty() || serverIP.isEmpty() || serialNumber.isEmpty()){
            TextView t  = findViewById(R.id.errMsg);
            t.setText("vid , cid, serverIP, deviceID都不能为空");
            return new HashMap<>();
        }
        Map<String, String> map = new HashMap<String, String>();
        map.put("cid", cid);
        map.put("vid", vid);
        map.put("ip", serverIP);
        map.put("id", adbPassserialNumber);

        return map;
    };


    public void testOpenMGTV()
    {
        Map<String, String> map = getPlayParams();
        String mgtvURI = String.format("imgotv://player?clipId=%s&plId=0&videoId=%s&start_time=0&from=mphone&pos=2",
                map.get("cid"),
                map.get("vid"));
        Intent mgtv = new Intent("android.intent.action.VIEW", Uri.parse(mgtvURI));
        startActivity(mgtv);
    }

    private void startForegroundService(){
        Map<String, String> map = getPlayParams();
        Intent serviceIntent = new Intent(this, ForegroundService.class);

        for(String key : map.keySet()){
            serviceIntent.putExtra(key, map.get(key));
        }
        startService(serviceIntent);
    }
    private void stopForegroundService(){
        stopService(new Intent(this, ForegroundService.class));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.test:
                testOpenMGTV();
                break;
            case R.id.startService:
                startForegroundService();
                break;
            case R.id.stopService:
                stopForegroundService();
                break;
        }

    }

    @Override
    protected  void onResume(){
        Log.d(TAG, "OnResume");
        super.onResume();
    }
}
